//@author A0096759E

package applogger;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;

import org.joda.time.DateTime;


public class AppLogger {
	
	private static final String APP_LOGGER_FILE = "ActivityLog.txt";
	private static final String LOG_TEMPLATE = "[%s] %s";
	private static final String NEW_LOG_CREATED_MESSAGE = "New log created on %s";
	private static final String DATETIME_FORMAT_ACTIVITY_LOG = "dd/MM/yyyy'T'HH:mm:ss";
	private static final String ERROR_IN_LOGGING = "Error in logging. Continue.";

	/**
	 * Clears the Activity Log if it exists, if not it creates a new file.
	 * Then it writes the time of creation of the new Activity Log.
	 */
	public static void clear() {
		try {
			String logTime = getCurrentDateTime();
			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(APP_LOGGER_FILE)));
			out.println(String.format(NEW_LOG_CREATED_MESSAGE, logTime));
		    out.println();
		    out.close();
		} catch (Exception e) {
		    System.err.println(ERROR_IN_LOGGING);
			e.printStackTrace();
		}
	}

	/**
	 * Appends a time-stamped activity log into the activitylog file.
	 * @param toLog
	 */
	public static void log(String toLog) {
		try {
			String logTime = getCurrentDateTime();
		    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(APP_LOGGER_FILE, true)));
		    out.println(String.format(LOG_TEMPLATE, logTime, toLog));
		    out.close();
		} catch (Exception e) {
		    System.err.println(ERROR_IN_LOGGING);
			e.printStackTrace();
		}
	}
	
	/**
	 * Returns the current dateTime
	 * @return current date time
	 */
	private static String getCurrentDateTime() {
		DateTime currentTime = new DateTime();
		return currentTime.toString(DATETIME_FORMAT_ACTIVITY_LOG);
	}
	
}
